package kerr

import "fmt"

// Check 检查错误, 若错误不为空则抛出panic
func Check(err error) {
	if err != nil {
		panic(err)
	}
}

// Must 必须成功执行hi, 若错误不为空则抛出panic
func Must[T any](v T, err error) T {
	Check(err)
	return v
}

// Try 捕获panic, 并返回error
func Try(fn func()) (err error) {
	defer func() {
		if v := recover(); v != nil {
			var ok bool
			err, ok = v.(error)
			if ok {
				return
			}
			err = fmt.Errorf("%v", v)
		}
	}()
	fn()
	return
}

// TryRet 捕获panic, 并返回error
func TryRet[T any](fn func() T) (T, error) {
	var v T
	err := Try(func() {
		v = fn()
	})
	return v, err
}
